<template>
  <div class="app-container">
    <div class="top-section-container">
      <div class="content-header">
        <h1>健康管理/<small>套餐管理</small></h1>
        <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>健康管理</el-breadcrumb-item>
          <el-breadcrumb-item>套餐管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="bottom-section-container">
      <div class="search-bar filter-container">
        <el-input
            v-model="searchForm.name"
            placeholder="套餐名称"
            clearable
            style="width: 15rem; margin-right: 0.625rem; margin-top: 10px;"
            @keyup.enter="handleSearch"
        ></el-input>
        <el-input
            v-model="searchForm.code"
            placeholder="套餐编码"
            clearable
            style="width: 15rem; margin-right: 0.625rem; margin-top: 10px;"
            @keyup.enter="handleSearch"
        ></el-input>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="success" @click="handleAdd">新增套餐</el-button>
      </div>

      <el-table :data="setmealList" style="width: 100%; margin-top: 20px;" border stripe>
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="name" label="套餐名称" width="150" align="center"></el-table-column>
        <el-table-column prop="code" label="套餐编码" width="120" align="center"></el-table-column>
        <el-table-column prop="helpCode" label="助记码" width="120" align="center"></el-table-column>
        <el-table-column prop="price" label="价格" width="100" align="center"></el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          background
          style="margin-top: 20px; text-align: right;"
      ></el-pagination>
    </div>

    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="700px"
        @close="handleDialogClose"
    >
      <el-form :model="setmealForm" :rules="setmealFormRules" ref="setmealFormRef" label-width="90px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="setmealForm.name"></el-input>
        </el-form-item>
        <el-form-item label="套餐编码" prop="code">
          <el-input v-model="setmealForm.code"></el-input>
        </el-form-item>
        <el-form-item label="助记码" prop="helpCode">
          <el-input v-model="setmealForm.helpCode"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="setmealForm.price" :min="0" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="图片URL" prop="img">
          <el-input v-model="setmealForm.img" placeholder="请输入图片URL"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="setmealForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="关联检查组" prop="checkgroupIds">
          <el-select
              v-model="setmealForm.checkgroupIds"
              multiple
              placeholder="请选择关联检查组"
              style="width: 100%;"
          >
            <el-option
                v-for="item in checkGroupList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSetmealForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// 假设这里引入了用于后端请求的 axios 或其他库
// import axios from 'axios';

// 搜索表单数据
const searchForm = reactive({
  name: '',
  code: '',
});

// 套餐列表数据
const setmealList = ref([]);

// 检查组列表数据 (用于套餐关联选择)
const checkGroupList = ref([]);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const setmealForm = reactive({
  id: null,
  name: '',
  code: '',
  helpCode: '',
  price: 0,
  img: '',
  remark: '',
  checkgroupIds: [], // 关联的检查组ID数组
});
const setmealFormRef = ref(null); // 表单引用，用于表单验证

// 表单验证规则
const setmealFormRules = reactive({
  name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入套餐编码', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }, { type: 'number', message: '价格必须为数字值', trigger: 'blur' }],
  checkgroupIds: [{ type: 'array', required: true, message: '请至少选择一个检查组', trigger: 'change' }],
});

// 获取套餐列表数据（模拟）
const fetchSetmealList = () => {
  // 实际项目中，这里会发送 Axios 请求到后端 API
  console.log('Fetching setmeal list with:', {
    ...searchForm,
    currentPage: pagination.currentPage,
    pageSize: pagination.pageSize,
  });

  // 模拟数据 (t_setmeal 结构: id, name, code, help_code, sex, img, remark, price)
  const mockData = Array.from({ length: 50 }).map((_, i) => ({
    id: i + 1,
    name: `体检套餐${i + 1}`,
    code: `T${String(i + 1).padStart(3, '0')}`,
    helpCode: `TC${String(i + 1).padStart(3, '0')}`,
    price: (i + 1) * 100,
    img: i % 2 === 0 ? 'https://via.placeholder.com/150/0000FF/FFFFFF?text=Setmeal' : '', // 模拟有图和无图
    remark: `这是体检套餐${i + 1}的详细说明。`,
    // 模拟关联的检查组ID，实际会从后端获取
    checkgroupIds: Array.from({ length: Math.floor(Math.random() * 3) + 1 }).map(() => Math.floor(Math.random() * 10) + 1)
  }));

  // 根据搜索条件过滤模拟数据
  let filteredData = mockData.filter(setmeal => {
    const nameMatch = searchForm.name ? setmeal.name.includes(searchForm.name) : true;
    const codeMatch = searchForm.code ? setmeal.code.includes(searchForm.code) : true;
    return nameMatch && codeMatch;
  });

  pagination.total = filteredData.length;
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  setmealList.value = filteredData.slice(start, end);
};

// 获取检查组列表数据（模拟）
const fetchCheckGroupList = () => {
  console.log('Fetching all check groups...');
  // 实际项目中，这里会发送 Axios 请求到后端 API /checkgroup/findAll
  const mockCheckGroups = Array.from({ length: 15 }).map((_, i) => ({
    id: i + 1,
    name: `检查组${i + 1}`,
    code: `G${String(i + 1).padStart(2, '0')}`,
  }));
  checkGroupList.value = mockCheckGroups;
};

// 搜索按钮点击
const handleSearch = () => {
  pagination.currentPage = 1; // 搜索时重置回第一页
  fetchSetmealList();
};

// 重置按钮点击
const handleReset = () => {
  searchForm.name = '';
  searchForm.code = '';
  pagination.currentPage = 1;
  fetchSetmealList();
};

// 新增套餐
const handleAdd = () => {
  dialogTitle.value = '新增套餐';
  // 重置表单
  Object.assign(setmealForm, {
    id: null,
    name: '',
    code: '',
    helpCode: '',
    price: 0,
    img: '',
    remark: '',
    checkgroupIds: [],
  });
  dialogVisible.value = true;
};

// 编辑套餐
const handleEdit = (row) => {
  dialogTitle.value = '编辑套餐';
  // 填充表单数据，确保深拷贝避免直接修改表格数据
  // 实际中这里会根据ID查询套餐详情，包括其关联的检查组ID
  // 假设row中已包含checkgroupIds
  Object.assign(setmealForm, { ...row });
  dialogVisible.value = true;
};

// 删除套餐
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除套餐 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 实际项目中发送删除请求
    // axios.delete(`/setmeal/delete/${row.id}`).then(() => {
    ElMessage.success('删除成功！');
    fetchSetmealList(); // 重新加载数据
    // }).catch(error => {
    //   ElMessage.error('删除失败！');
    //   console.error(error);
    // });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 提交新增/编辑表单
const submitSetmealForm = () => {
  setmealFormRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中发送请求
      const apiEndpoint = setmealForm.id ? '/setmeal/update' : '/setmeal/add';
      console.log('Submitting setmeal form:', setmealForm);

      // axios.post(apiEndpoint, setmealForm).then(() => {
      ElMessage.success(setmealForm.id ? '更新成功！' : '新增成功！');
      dialogVisible.value = false;
      fetchSetmealList(); // 重新加载数据
      // }).catch(error => {
      //   ElMessage.error('操作失败！');
      //   console.error(error);
      // });
    } else {
      ElMessage.error('请检查表单填写是否完整正确！');
      return false;
    }
  });
};

// 弹窗关闭时清空表单校验状态
const handleDialogClose = () => {
  if (setmealFormRef.value) { // 确保ref已赋值
    setmealFormRef.value.resetFields();
  }
};

// 分页每页数量改变
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  fetchSetmealList();
};

// 分页当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  fetchSetmealList();
};

// 组件挂载时加载数据
onMounted(() => {
  fetchSetmealList();
  fetchCheckGroupList(); // 加载检查组列表
});
</script>

<style scoped>
/* 容器基本样式，模仿 app-container */
.app-container {
  padding: 0; /* 外部容器不设 padding，让内部 section 控制 */
  box-sizing: border-box;
}

/* 顶部区域样式 */
.top-section-container {
  background-color: #f9f9f9; /* 浅灰色背景 */
  padding: 1.25rem 1.25rem 0.625rem; /* 内边距 */
  border-bottom: 3px solid #409EFF; /* 蓝色底部边框 */
  margin-bottom: 1.25rem; /* 与下方内容区域的间距 */
  box-shadow: 0 2px 4px rgba(0,0,0,0.05); /* 底部阴影 */
}

/* 底部内容区域样式 */
.bottom-section-container {
  background-color: #ffffff; /* 白色背景 */
  padding: 1.25rem; /* 内边距 */
  box-shadow: 0 2px 4px rgba(0,0,0,0.05); /* 阴影 */
  border-radius: 0.25rem; /* 圆角 */
  margin: 0 1.25rem 1.25rem 1.25rem; /* 左右和底部留白 */
}

/* 现有样式调整 */
.content-header {
  padding-bottom: 0.625rem; /* 保持面包屑和标题的底部间距 */
}

/* 搜索/过滤容器，去除之前可能添加的边框或阴影 */
.search-bar.filter-container {
  padding: 0; /* 在 bottom-section-container 中，filter-container 不再需要额外的 padding */
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  /* 移除之前为模拟分割线而添加的样式 */
  border-bottom: none;
  padding-bottom: 0;
  box-shadow: none;
}

/* 确保表格操作列按钮间距 */
.el-table .el-button + .el-button {
  margin-left: 5px;
}

.dialog-footer {
  text-align: right;
  margin-top: 1.25rem;
}
</style>